import {
  getTaskCount,
  getTaskList,
  setTaskFinish,
  getPatientByTeacher,
  getPatientByDoctor,
  addTasks,
  delTasks,
  editTasks
} from '../../api/index'
import {
  classifyType,
  taskCountType,
  taskType,
  findTypeByLabel,
  userType,
  findTypeByValue,
  frequencyType
} from '../../utils/type';
import {
  formatTimeTask
} from '../../utils/util'
const app = getApp()

Page({
  data: {
    active: 0,
    logined: true,
    baseCls: 'page_account',
    avatar_icon: '/assets/images/avatar.png',
    tab_active: 0,
    filter: {
      countType: undefined,
      classify: undefined
    },
    currentDate: '',
    taskCount: {
      onGoing: 0,
      Finish: 0,
      Delay: 0
    },
    loading: true,
    sendTaskKey: '今日任务',
    receiveTaskKey: '今日任务',
    addshow: false,
    disabled: false,

    taskType,
    frequencyType,
    repeat_checked: false,
    sms_checked: false,
    editshow: false,
    infoshow: false,
    TaskForm: {},
    finishIds: [],
    searchValue: ''
  },
  onShow: function () {
    var that = this;
    that.getTabBar().init();
    let userInfo = wx.getStorageSync('userInfo');
    if (userInfo) {
      that.setData({
        logined: true,
        show: false,
        userInfo: userInfo
      })
      that.taskCount();
      that.MyPatient();
      setTimeout(function () {
        that.getTabList()
      }, 150)
    }
  },

  /*
   * 搜索value
   */
  onChangeSearch(event) {
    this.setData({
      searchvalue: event.detail
    })
  },

  /*
   * 任务搜索
   */
  searchTask() {
    var that = this;
    setTimeout(function () {
      that.getTabList()
    }, 150)
  },

  /**
   * search clear
   */
  searchClear() {
    this.setData({
      searchvalue: ''
    })
    setTimeout(() => {
      this.getTabList()
    }, 150)
  },

  /* tab 切换 */
  onChange(e) {
    this.setData({
      tab_active: e.detail.index
    })

    this.taskList()
  },

  /**
   * 全部任务
   */
  taskList(e) {
    const searchValue = this.data.searchvalue;
    const classify = classifyType[this.data.tab_active]
    const dataKey = `${classify.key}Key`
    let key = this.data[dataKey]
    if (typeof (e) !== 'undefined') {
      key = e.currentTarget.dataset.key;
    }

    const newData = {}
    newData[dataKey] = key
    this.setData(newData)

    const countType = findTypeByLabel(key, taskCountType)
    const taskListKey = `allTaskList.${classify.key}.${countType.key}`
    const params = {
      pageNum: 1,
      pageSize: 999,
      classify: classify?.value,
      type: countType?.value
    }
    if(searchValue){
      params.realName = searchValue
    }
    
    getTaskList(params).then(res => {
      const rows = res.rows;
      const unfinishRows = [];
      const finishRows = [];
      rows.forEach(item => {
        if (item.isComplete) {
          finishRows.push(item)
        } else {
          unfinishRows.push(item)
        }
      })

      const data = {
        filter: {
          countType,
          classify
        },
      }
      data[taskListKey] = {
        rows: [...unfinishRows, ...finishRows],
        finishRows: finishRows,
        unfinishRows: unfinishRows
      }
      this.setData(data)
      setTimeout(() => {
        this.setData({
          finishIds: finishRows.map(item => item.id) || [],
        })
      }, 150)
    })

    this.taskCount()
  },

  // receive_task
  finishMyTask(event) {
    let id = event.target.id
    const filter = this.data.filter
    const unfinishRows = this.data.allTaskList[filter.classify.key][filter.countType.key].unfinishRows
    const finishRows = this.data.allTaskList[filter.classify.key][filter.countType.key].finishRows
    const finishIds = this.data.finishIds
    const taskListKey = `allTaskList.${filter.classify.key}.${filter.countType.key}`
    const isComplete = finishIds.includes(id)

    let newFinishIds = []
    let newFinishRows = []
    let newUnfinishRows = []

    if(isComplete){
      const row = finishRows.find(item => item.id === id)
      newFinishIds = finishIds.filter(item => item !== id)
      newFinishRows = finishRows.filter(item => item.id !== id)
      newUnfinishRows = [
        ...unfinishRows,
        row
      ]
    }else{
      const row = unfinishRows.find(item => item.id === id)
      newFinishIds = [
        ...finishIds,
        id
      ]
      newFinishRows = [
        ...finishRows,
        row
      ]
      newUnfinishRows = unfinishRows.filter(item => item.id !== id)
    }

    const data = {}
    
    data[taskListKey] = {
      rows: [...newUnfinishRows, ...newFinishRows],
      finishRows: newFinishRows,
      unfinishRows: newUnfinishRows,
    }
    this.setData(data);

    setTimeout(() => {
      this.setData({
        finishIds: newFinishIds
      })
    }, 100)

    // 提交变动
    this.Updatestate(id, !isComplete ? 1 : 0)
  },

  /**
   * 更新任务状态
   * */
  Updatestate(id, type) {
    setTaskFinish({
      id,
      isComplete: type
    }).then(res => {
      this.taskCount()
      console.log(res);
    })
  },

  /*
   * 任务数据统计
   * onGoing 待完成 / Finish 已完成 / delay 已延期
   */
  taskCount() {
    let that = this;

    getTaskCount().then(res => {
      const data = res.data;
      that.setData({
        taskCount: {
          onGoing: data.progress,
          Delay: data.delay,
          Finish: data.complete
        },
        receiveCount: data.receive,
        sendCount: data.send
      })
    })
  },


  /**
   *  添加任务弹窗取消
   */
  hideshow() {
    this.setData({
      addshow: false,
      editshow: false,
      infoshow: false,
      sms_checked: false
    })
    wx.setPageStyle({
      style: {
        overflow: 'auto'
      }
    })
  },

  /**
   *  添加任务弹窗显示
   */
  addTaskShow() {
    this.setData({
      TaskForm: {},
      teacher: '',
      addshow: true
    })
    wx.setPageStyle({
      style: {
        overflow: 'hidden'
      }
    })
  },

  /**
   * 新增任务
   * */
  addTaskSubmit() {
    let that = this
    let fields = this.data.TaskForm
    const data = { ...fields }
    data.isRepeat = data.isRepeat ? 1: 0
    data.senderId = this.data.userInfo.id
    data.isMsg = data.isMsg ? 1: 0
    data.type = findTypeByLabel(data.type, taskType).value
    
    if(data.isRepeat){
      delete data.taskDate
      data.frequency = findTypeByLabel(data.frequency, frequencyType).value
    }else{
      delete data.beginDate
      delete data.endDate
    }

    addTasks(data).then(res => {
      wx.showToast({
        title: '新增成功',
        icon: 'none',
        duration: 2000
      })
      that.hideshow()
      that.taskCount()
      that.getTabList()
      that.setData({
        TaskForm: ''
      })
    })
  },
  /**
   *  任务详情
   * */
  getTaskInfo(e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    let taskList = this.data.allTaskList[this.data.filter.classify.key][this.data.filter.countType.key]
    let currTask = taskList.rows.filter(item => item.id === id)
    if (currTask.length > 0) {
      currTask = currTask[0]
    }
    let userLabel = findTypeByValue(currTask.executorUserType, userType)?.label || '-'
    let executor = `${userLabel}：${currTask.executorUserName}`
    let frequency = findTypeByValue(currTask.frequency, frequencyType)?.label || '-'

    that.setData({
      infoshow: true,
      TaskInfo: {
        ...currTask,
        executor,
        frequency
      }
    })

    wx.setPageStyle({
      style: {
        overflow: 'hidden'
      }
    })
  },
   /**
   *  编辑任务弹窗弹出
   * */
  editTaskShow(e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    let taskList = this.data.allTaskList[this.data.filter.classify.key][this.data.filter.countType.key]
    let currTask = taskList.rows.filter(item => item.id === id)
    if (currTask.length > 0) {
      currTask = currTask[0]
    }
    let editTask = {
      ...currTask
    }
    editTask.type = findTypeByValue(editTask.type, taskType)?.label || taskType[0].label
    editTask.frequency = findTypeByValue(editTask.frequency, frequencyType)?.label || frequencyType[0].label

    // 筛选执行者
    const patients = this.data.MyPatient.filter(item => item.id === editTask.executorId)
    if(patients.length > 0){
      editTask.teacherUserName = patients[0].teacherName
      editTask.teacherId = patients[0].teacherId
    }

    that.setData({
      editshow: true,
      TaskForm: editTask,
      teacher: editTask.teacher.teacherName,
    })
    
    wx.setPageStyle({
      style: {
        overflow: 'hidden'
      }
    })
  },
  /**
   * 编辑任务提交
   * */
  editTaskSubmit() {
    let that = this;
    that.setData({
      editdisabled: true
    })
    let fields = this.data.TaskForm
    if(JSON.stringify(fields) === '{}' || typeof fields === 'undefined'){
      wx.showToast({
        title: '任务没有修改，无法提交',
        icon: 'none',
        duration: 2000
      })
      that.setData({
        editdisabled: false,
      })
      return;
    }

    const data = { ...fields }
    data.senderId = this.data.userInfo.id
    data.frequency = findTypeByLabel(data.frequency, frequencyType).value
    data.type = findTypeByLabel(data.type, taskType).value
    data.isRepeat = data.isRepeat ? 1: 0
    data.isMsg = data.isMsg ? 1: 0

    if(data.isRepeat){
      delete data.taskDate
    }else{
      delete data.beginDate
      delete data.endDate
    }

    editTasks(data).then(res => {
      that.setData({
        editdisabled: false,
        TaskForm: ''
      })
      wx.showToast({
        title: '更新成功',
        icon: 'none',
        duration: 2000
      })
      that.hideshow();
      that.taskCount();
      setTimeout(function () {
        that.getTabList()
      }, 200)
    })

  },
  /**
   * 删除任务
   * */
  delTask() {
    var that = this;
    var id = that.data.id;

    delTasks([id]).then(res => {
      wx.showToast({
        title: '删除成功',
        icon: 'none',
        duration: 2000
      })
      that.taskCount();
      that.hideshow();
      that.getTabList()
    })
  },

  /* 任务类型 */
  setTaskType(e) {
    this.setData({
      'TaskForm.type': findTypeByValue(e.detail.value.value, taskType)?.label || taskType[0].label
    })
  },
  /* 任务日期 */
  setTaskDate(e) {
    this.setData({
      'TaskForm.taskDate': formatTimeTask(e.detail.value)
    })
  },
  /* 任务时间 */
  setTaskTime(e) {
    this.setData({
      'TaskForm.taskTime': e.detail.value
    })
  },
  /* 重复 */
  repeat_checked(e) {
    this.setData({
      'TaskForm.isRepeat': e.detail
    })
  },
  /*开始日期 */
  setStartTime(e) {
    this.setData({
      'TaskForm.beginDate': formatTimeTask(e.detail.value)
    })
  },
  /*结束日期 */
  setEndTime(e) {
    this.setData({
      'TaskForm.endDate': formatTimeTask(e.detail.value)
    })
  },
  /* 频次 */
  setFrequency(e) {
    this.setData({
      'TaskForm.frequency': findTypeByValue(+e.detail.value.value, frequencyType)?.label
    })
  },
  /* 短信提醒 */
  setSMS(e) {
    this.setData({
      'TaskForm.isMsg': e.detail
    })
  },
  /* 内容 */
  setContent(e){
    this.setData({
      'TaskForm.content': e.detail
    })
  },
  /* 患者 */
  setTaskPatient(e) {
    const data = e.detail.value
    this.setData({
      teacher: data.teacherName,
      'TaskForm.executorId': data.id
    })
  },

  /*
   * 我的患者
   */
  MyPatient() {
    let that = this;
    let type = that.data.userInfo.type;
    let func = type.key === 'teacher' ? getPatientByTeacher : getPatientByDoctor

    func().then(res => {
      if (res.rows.length > 0) {
        const patients = res.rows.map(item => {
          return {
            id: item.id,
            name: item.realName,
            teacherName: item.teacherName,
            teacherId: item.teacherId
          }
        })
        that.setData({
          MyPatient: patients
        })
      }
    })
  },

  getTabList() {
    this.taskList();
  },

  /**
   * 跳转首页
   */
  goHome() {
    wx.reLaunch({
      url: '/pages/index/index'
    })
  },

  noop(e) {
  },

})